#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/time.h>

int main(int argc, char const *argv[])
{
    // if(argc < 2){
    //     printf("usage err\n");
    //     return -1;
    // }
    int sockfd = socket(AF_INET, SOCK_STREAM, 0); // ipv4,tcp
    if (sockfd == -1)
    {
        perror("sock err");
        return -1;
    }
    // 服务器地址:IP 端口号
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    // server_addr.sin_port =htons(atoi(argv[2]));
    server_addr.sin_port = htons(8888);

    // server_addr.sin_addr.s_addr=inet_addr(argv[1]);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    printf("IP=%s\n", inet_ntoa(server_addr.sin_addr));
    socklen_t addrlen = sizeof(server_addr);

    // 连接
    if (connect(sockfd, (struct sockaddr *)&server_addr, addrlen) < 0)
    {
        perror("coonet err");
        close(sockfd);
        return -1;
    }
    printf("connet  success\n");

    struct timeval tv;
    tv.tv_sec = 5; // 设置5秒时间
    tv.tv_usec = 0;
    socklen_t size_tv=sizeof(tv);
    setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, size_tv);

    // 收发数据
    char buf[64] = {0};
    int temp = 0;
    while (1){
        int ret=-1;
        ret =recv(sockfd,buf,sizeof(buf),0);
        if(ret < 0){
            perror("recv err");
            continue;
        }else if(ret > 0){
            printf("recv data:%s\n",buf);
        }else{
            printf("perr quit\n");
            break;
        }
        scanf("%s", buf);
        if (strcmp(buf, "quit") == 0)
        {
            printf("sever quit\n");
            break;
        }

        if (send(sockfd, buf, 64, 0) == -1)
        { // send 不一定会一次全部发送完，分多次发送完
            perror("send err");
            break;
        }


    
    }

    // 关闭
    close(sockfd);

    return 0;
}
